import DataBus from "../databus";
import {PageStatus} from "../page_status";
import XmlManager from "../manager/xml_manager";

const screenWidth = window.innerWidth
const screenHeight = window.innerHeight

const BG_IMG_SRC = 'images/bg.jpg'
const BG_WIDTH = 640
const BG_HEIGHT = 1136

const databus = new DataBus()
const xmlManager = new XmlManager()
/**
 * 游戏背景类
 * 提供update和render函数实现无限滚动的背景功能
 */
export default class Background  {
  constructor(ctx) {
    this.img = new Image()
    this.img.src = 'images/bg.jpg'

    this.width = BG_WIDTH
    this.height = BG_HEIGHT

    this.x = 0
    this.y = 0

    this.visible = true

    this.top = 0
    this.render(ctx)
  }

  /**
   * 将精灵图绘制在canvas上
   */
  drawToCanvas(ctx) {
    if (!this.visible) return

    ctx.drawImage(
        this.img,
        this.x,
        this.y,
        this.width,
        this.height
    )
  }
  update() {
    var imgAttribute
    var w,h
    if(databus.gameStatus===PageStatus.GameIntroduce){
      imgAttribute = xmlManager.obtainAttributes(xmlManager.sceneIntroduce.component.displayList.image,"img_bg");
      [w,h] = xmlManager.sceneIntroduce.component._attributes.size.split(",");
    } else if( databus.gameStatus===PageStatus.RouteSelect){
      imgAttribute = xmlManager.obtainAttributes(xmlManager.sceneSelectRoute.component.displayList.image,"img_bg");
      [w,h] = xmlManager.sceneSelectRoute.component._attributes.size.split(",")
    }else if( databus.gameStatus===PageStatus.GameMainMenu){
      [w,h] = xmlManager.sceneMainGame.component._attributes.size.split(",")
      imgAttribute = xmlManager.obtainAttributes(xmlManager.sceneMainGame.component.displayList.image,"img_bg")
    }else {
      [w,h] = xmlManager.sceneStartGame.component._attributes.size.split(",")
      imgAttribute = xmlManager.obtainAttributes(xmlManager.sceneStartGame.component.displayList.image,"img_bg")

    }

    this.width = w
    this.height = h
    this.img.src = xmlManager.assetName(imgAttribute.fileName);

  }

  /**
   * 背景图重绘函数
   * 绘制两张图片，两张图片大小和屏幕一致
   * 第一张漏出高度为top部分，其余的隐藏在屏幕上面
   * 第二张补全除了top高度之外的部分，其余的隐藏在屏幕下面
   */
  render(ctx) {
    ctx.drawImage(
      this.img,
      0,
      0,
      this.width,
      this.height,
      0,
      this.top,
      screenWidth,
      screenHeight
    )
  }
  onTouchEvent(type, x, y, callback) {
  }
}
